<?php


namespace App\Repositories\Game\Castle;

use App\Models\GameDB\Castle\CastleLossList;
use App\Models\GameDB\Castle\CastlePool;
use App\Models\GameDB\Castle\GameConfig;
use App\Traits\Singleton;
use App\Exceptions\BasicException;
use Illuminate\Database\Eloquent\Builder;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class CastleSettingRepository
{
    use Singleton;
    private $name = 'castle';

    /**
     * @param bool $fail
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws BasicException 获取糖果城堡的配置
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function setting(bool $fail = false)
    {
        // 存redis
        $key = 'castle:setting';
        $pool_key = 'castle:pool_coin';
        $redis = app('redis');
        if (!$redis->exists($key)) {
            $query = GameConfig::query();
            $model = $query->where('name', $this->name)->get()->toArray();
            $data = [];
            foreach ($model as $val) {
                $data[$val['key']] = $val['value'];
            }
            if(!$redis->exists($pool_key)){
                $pool_coin = CastlePool::query()->where('id', 1)->value('coin');
                $redis->set($pool_key, $pool_coin);
                $data['change'] = $pool_coin ?? 0;
            }else{
                $data['change'] = $redis->get($pool_key) ?? CastlePool::query()->where('id', 1)->value('coin');
            }
            $data['change'] = $redis->get($pool_key) ?? 0;
            $loss_lv = CastleLossList::query()->where('enabled', 1)->orderBy('loss_lv', 'desc')->first();
            $data['loss_lv'] = $loss_lv['loss_lv'] ?? 0;
            $redis->set($key, json_encode($data));
        } else {
            $data = json_decode($redis->get($key), true);
        }

        if (!$data) {
            throw new BasicException(-1, "游戏配置中");
        }
//        if ($data['is_open'] != '1') {
//            throw new BasicException(-1, "游戏未开启");
//        }
        return $data;
    }
}
